//
//  TasksVC.swift
//  DianXia
//
//  Created by you&me on 2017/12/20.
//  Copyright © 2017年 you&me. All rights reserved.
//

import UIKit



class TasksVC: UIViewController {
    enum TaskType {
        case AllTask
        case IngTask
    }

    @IBOutlet weak var backBtn: UIButton!
    @IBOutlet weak var tasksTab: UITableView!
    var taskType = TaskType.AllTask {
        didSet {
            switch taskType {
            case .AllTask:
                taskArray = UserTasks.share.tasks
            default:
                taskArray = UserActivingTasks.share.tasks
            }
        }
    }
    var taskArray = [BCTask]()
    let dispose = DisposeBag()
    let vm = TasksVM()

    override func viewDidLoad() {
        super.viewDidLoad()
        tasksTab.tableFooterView = UIView()
        backBtn.rx.tap
            .subscribe({ _ in
                let vc = UIStoryboard.initialViewControllerFromStoryboard(.Home) as! UIViewController
                UIApplication.shared.keyWindow?.rootViewController = vc
            })
            .disposed(by: dispose)
        vm.isReload.asObservable()
            .subscribe(onNext: { (isReload) in
                if isReload {
                    self.tasksTab.reloadData() //刷新
                }
            })
            .disposed(by: dispose)
    }

}

extension TasksVC: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return taskArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NeedAuthenCell", for: indexPath) as! NeedAuthenCell
        let model = taskArray[indexPath.row]
        cell.cellTitle.text = "售卖机编号：\(model.code ?? "") 任务：\(model.type ?? ""), 位置：\(model.address ?? "")"
        if model.progress == "2" {
            cell.cellNoBtn.setTitle("进行中", for: .normal)
            cell.cellOKBtn.isHidden = true
            cell.cellNoBtn.isEnabled = false
        }else {
            cell.cellNoBtn.setTitle("接受", for: .normal)
            cell.cellOKBtn.isHidden = false
            cell.cellNoBtn.isEnabled = true
        }
        // 拒绝按钮
        cell.cellOKBtn.rx.tap
            .subscribe({ [weak self] _ in self?.vm.acceptOrRefuseTask("refuseTask",  model.no ?? 0 , indexPath.row) })
            .disposed(by: dispose)
        // 接受按钮
        cell.cellNoBtn.rx.tap
            .subscribe({ [weak self] _ in self?.vm.acceptOrRefuseTask("acceptTask",  model.no ?? 0, indexPath.row) })
            .disposed(by: dispose)
        return cell

    }


}
